# coding:utf-8
'''
Created on 2011-12-8

@author: bobobo80
'''
from M2Crypto.SSL.SSLServer import ThreadingSSLServer
from M2Crypto import SSL
import SocketServer
import threading
import time
import twitter
import pushData

global_isShutdown = False

class MyTCPHandler(SocketServer.BaseRequestHandler):
        """
        The RequestHandler class for our server.
        
        It is instantiated once per connection to the server, and must
        override the handle() method to implement communication to the
        client.
        """
        
        def setup(self):
                self.isAuthentication = False
                self.isClose = False
                self.twitter = twitter.twitterReq()
                global global_isShutdown
                global_isShutdown = False
        
        def handle(self):
                try:
                        while 1:
                                time.sleep(0.5)
                                global global_isShutdown
                                if global_isShutdown:
                                        break
                                # self.request is the TCP socket connected to the client
                                data = self.request.recv(1024)
                                # check data is empty
                                if data == '':
                                        print 'data empty'
                                        time.sleep(0.5)
                                        continue
                                #print "{} wrote:".format(self.client_address[0]), data
                                #self.request.send('rec')
                                print 'data:',data
                                # Separate data / get prefix
                                if len(data)>4:
                                        prefix = data[0:3]
                                        data = data[3:].strip()
                                else:
                                        # unknown request
                                        self.request.send('ERR unknown request')
                                        
                                # 
                                if prefix == 'AUT':
                                        self.response_AUT(data)
                                # disconnect
                                elif prefix == 'BYE': 
                                        self.response_BYE(data)
                                # check authentication
                                elif self.isAuthentication:
                                        # Get some informations
                                        if prefix == 'GET':
                                                self.response_GET(data)
                                        # post some informaions
                                        elif prefix == 'POS':
                                                self.response_POS(data)
                                        # error information
                                        elif prefix == 'ERR':
                                                self.response_ERR(data)
                                        # unknown prefix
                                        else:
                                                self.response_UNKNOWN(data)
                                # have not authentication        
                                else:
                                        self.request.send('AUT have not authentication')
                                
                                # check whether close
                                if self.isClose:
                                        print 'close one connect'
                                        break
                                
                except Exception,e:
                        print 'err:',e
                        self.request.send('BYE BYE')
                
        def finish(self):
                print 'finish'
                
        # response def 
        def response_AUT(self, data):
                if data == 'password':
                        self.isAuthentication = True
                        self.request.send('AUT authentication')
                else:
                        self.request.send('AUT worry password')   
                
        def response_GET(self, data):
                if data == 'timeline':
                        # print 'go to twitter.com to get timeline'
                        resp = pushData.PUSHDATA.homeTimeline
                        print 'got it. send.'
                        self.request.send('POS '+str(resp))
                
        def response_POS(self, data):
                pass
                
        def response_BYE(self, data):
                print 'BYE BYE'
                self.isClose = True
                
        def response_ERR(self, data):
                pass
                
        def response_UNKNOWN(self, data):
                self.request.send('ERR ' + 'unknown request: ' + data)

class serverControl(threading.Thread):
        def __init__(self, server):
                threading.Thread.__init__(self)
                self.server = server
        
        def run(self):
                print 'start'
                self.start_server()
                        
        def start_server(self):
                self.server.serve_forever()
                
        def stop_server(self):
                global global_isShutdown
                global_isShutdown = True
                self.server.shutdown()
                print 'stop'

if __name__ == "__main__":
        addr = ("", 9999)
        ctx = SSL.Context('sslv3')
        ctx.load_cert(certfile="server.crt", keyfile="server.key")
        # Create the server, binding to  on port 9999
        server = ThreadingSSLServer(addr, MyTCPHandler, ctx)
        server_ctrl = serverControl(server)
        server_ctrl.start()
        time.sleep(30)
        server_ctrl.stop_server()
        